import { ProductInfo } from '@/lib/dianxiaomi';
import { waitEleRender } from '@/lib/utils';
import { CategoryItem } from '@/store';
import JSZip from 'jszip';

export default defineContentScript({
  matches: ['https://www.dianxiaomi.com/web/popTemu/quoteEdit*'],
  world: 'MAIN',
  async main() {
    const url = location.href;
    const category = new URL(url).searchParams.get('category');
    if (!category) {
      return;
    }
    const ele = await waitEleRender(
      '.category-item .ant-form-item-control-input-content .ant-btn-primary',
      5000,
    );
    const id = 'attributes-extract';
    let extractEle = document.getElementById(id);
    if (extractEle) {
      return;
    }

    // 屏蔽掉 loading 框
    const style = document.createElement('style');
    style.innerHTML = `
      #dPageLoading {
        display: none;
      }
    `;
    document.head.appendChild(style);

    const categoryItem = {} as CategoryItem & {
      prefine: boolean;
      isAdd: boolean;
    };

    const originSend = window.XMLHttpRequest.prototype.send;
    window.XMLHttpRequest.prototype.send = function (...args) {
      const data = args[0];
      if (data instanceof FormData) {
        const file = data.get('file') as File;
        if (file && file.type === 'application/zip') {
          // 把 file 进行 zip 解压缩
          const zip = new JSZip();
          zip
            .loadAsync(file)
            .then((zip) => {
              zip.forEach((relativePath, zipEntry) => {
                zipEntry.async('string').then((content) => {
                  // console.log(`File: ${relativePath}`);
                  // console.log(content);
                  const data = JSON.parse(content) as ProductInfo;
                  // console.log(data);
                  categoryItem.categoryId = data.categoryId;
                  categoryItem.attributes = data.attributes;
                  const spanEle = document.querySelector(
                    '#productBasicInfo form > .category-item span.ant-select-selection-item',
                  );
                  categoryItem.categoryName = spanEle?.textContent || '';
                  if (window.opener) {
                    const attributesExtractEvent = new CustomEvent('attributes-extract', {
                      detail: categoryItem,
                    });
                    window.opener.dispatchEvent(attributesExtractEvent);
                  }
                });
              });
            })
            .catch((error) => {
              console.error('Error loading zip file:', error);
            });
        }
        // 不是真的提交产品信息
        return;
      }
      return originSend.apply(this, args);
    };

    function extract(isAdd = false) {
      const saveButton = document.querySelector(
        'div.footer > div > button:nth-child(5)',
      ) as HTMLButtonElement;
      const prefine = new URL(url).searchParams.get('prefine');
      categoryItem.prefine = prefine === '1' ? true : false;
      categoryItem.isAdd = isAdd;
      categoryItem.id = category!;
      saveButton.click();
    }

    if (ele) {
      extractEle = ele.cloneNode() as HTMLButtonElement;
      const extractEle2 = ele.cloneNode() as HTMLButtonElement;
      if (extractEle) {
        extractEle.id = id;
        extractEle.classList.remove('categoryModalShow');
        extractEle.textContent = '提取分类属性';
        extractEle.style.display = 'inline-block';
        extractEle2.classList.remove('categoryModalShow');
        extractEle2.textContent = '提取并新增分类属性';
        extractEle2.style.display = 'inline-block';
        extractEle2.style.margin = '0 0 0 5px';
        ele.parentElement?.appendChild(extractEle);
        ele.parentElement?.appendChild(extractEle2);
        extractEle.addEventListener('click', () => {
          extract();
        });
        extractEle2.addEventListener('click', () => {
          extract(true);
        });
      }
    }
  },
});
